
package com.tanker.common.utils.microRental.common;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class HttpBlockPostSender implements HttpSender{
	
	private final static Logger logger = LoggerFactory.getLogger(HttpBlockPostSender.class);
	private HttpClient httpClient;
	
	public HttpBlockPostSender(){
		httpClient =  HttpClients.createDefault();
	}
	
	public String send(Map<String, String> parameter, String url){
		HttpPost postMethod = new  HttpPost(url);
		
		List<NameValuePair> formparams = new ArrayList<NameValuePair>();
		if(parameter != null){
			for (Iterator<String> iterator = parameter.keySet().iterator(); iterator.hasNext();) {
				String key = iterator.next();
				formparams.add(new BasicNameValuePair(key, parameter.get(key)));  
			}
		}
		StringBuffer returnData = new StringBuffer();
		
		try {
			UrlEncodedFormEntity uefEntity = new UrlEncodedFormEntity(formparams, "UTF-8");
			postMethod.setEntity(uefEntity);
			
			HttpResponse response = httpClient.execute(postMethod);
			logger.info(url + "  status:"+response.getStatusLine().getStatusCode());
			
			HttpEntity entity = response.getEntity();
			
			if(entity != null){
				returnData.append(EntityUtils.toString(entity));
			}
			
			EntityUtils.consume(entity);
			 
			postMethod.releaseConnection();
			
		} catch (Exception e) {
			logger.error("send message  error", e);
			return null;
		}
		
		return returnData.toString();
	}
}
